package com.ecloud.gardensterminal.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @author Squbi
 */
public class MacAddressBase {
    private MacAddressBase() {
    }

    private static String localMacAddress = null;

    public static String getLocal() {
        if (localMacAddress == null) {
            synchronized (MacAddressBase.class) {
                try {
                    localMacAddress = countLocalMacAddress();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return localMacAddress;
    }

    private static String countLocalMacAddress() throws SocketException {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            byte[] address = networkInterfaces.nextElement().getHardwareAddress();
            if (address != null && address.length > 0) {
                return analysisAddress(address);
            }
        }
        return null;
    }

    public static String getMacAddress(InetAddress ia) throws SocketException {
        byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
        return analysisAddress(mac);
    }

    public static String analysisAddress(byte[] address) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < address.length; i++) {
            if (i != 0) {
                sb.append("_");
            }
            //字节转换为整数
            int temp = address[i] & 0xff;
            String str = Integer.toHexString(temp);
            if (str.length() == 1) {
                sb.append("0");
            }
            sb.append(str);
        }
        return sb.toString().toUpperCase();
    }
}
